// pages/login/index.js
const app = getApp()
var call = require("../../utils/request.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    code: '', // 登录后的code
    checked: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.Login();
  },
  // 去用户协议
  one(){
    wx.navigateTo({
      url: '/pages/agreement/one/index'
    })
  },
  // 去隐私政策
  two(){
    wx.navigateTo({
      url: '/pages/agreement/two/index'
    })
  },
  onChange(event) {
    this.setData({
      checked: event.detail,
    });
  },
  // 获取code
  Login () {
    wx.login({
      success: res => {
        console.log(res.code)
        this.setData({ code: res.code })
      }
    })
  },
  // 用户授权-获取手机
  getPhoneNumber(e) {

    var msg = e.detail.errMsg;
    var encryptedData = e.detail.encryptedData;
    var iv = e.detail.iv;
    if (msg == 'getPhoneNumber:ok') {
      wx.checkSession({
        success: res => {
          this.submitPu(encryptedData,iv);
        },
        fail: err => {
　　　　　 wx.showToast({ icon: 'none',title: '登录超时请重试' })
          this.Login();　　
　　　　}
      })
    }
  },
  // 提交
  submitPu (encryptedData,iv) {
    // 发送 res.code 到后台换取 openId, sessionKey, unionId
    call.request('/api/user/login', {
      encryptedData,
      iv,
      code: this.data.code,
      type: 1,
      app_id: 1,
    },
    (data) => {
      if(data.code == 1){
        wx.setStorageSync('token', data.data.token);
        if(data.data.wechat_openid == ''){
            wx.reLaunch({
              url: '/pages/auth/index'
            })
        }else{
            wx.reLaunch({
              url: '/pages/home/index'
            })
        }
      }else{
        wx.showToast({ icon: 'none',title: data.msg });
        this.Login();
      }
    },function (err) {
      console.log(err)
    })
  },
})